package com.transsion.clouddemo.core.config

import android.app.Service
import android.content.Intent
import android.os.IBinder
import androidx.fragment.app.viewModels
import java.io.BufferedReader
import java.io.InputStreamReader

class LogcatService : Service() {

    private var logThread: Thread? = null

    // ViewModel 初始化
    private val logViewModel: LogViewModel = LogViewModel


    override fun onBind(intent: Intent?): IBinder? {
        return null
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        startLogcat()
        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
        stopLogcat()
    }

    private fun startLogcat() {
        if (logThread?.isAlive == true) return

        logThread = Thread {
            try {
                // 使用更宽泛的过滤条件进行测试
                val process = Runtime.getRuntime().exec("logcat okhttp.OkHttpClient:* zhangxin:* *:S")
                val bufferedReader = BufferedReader(InputStreamReader(process.inputStream))

                var line: String?
                // 使用一个 StringBuilder 来批量处理日志
                val logBatch = StringBuilder()

                while (bufferedReader.readLine().also { line = it } != null) {
                    val logLine = line ?: continue
                    logBatch.append("$logLine\n")

                    if (logBatch.length > 1024) { // 当日志批量达到一定大小时更新
                        logViewModel.updateLogEntries(listOf(LogEntry(logBatch.toString())))
                        logBatch.clear()
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        logThread?.start()
    }


    private fun stopLogcat() {
        logThread?.interrupt()
        logThread = null
    }
}
